<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
		</view>
		<view class="uni-container">
			<el-row v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
				element-loading-background="rgba(0, 0, 0, 0.8)">
				<el-card>
					<div slot="header" class="clearfix">
						<span class="card-item-first card-item" :class="(active==0?'card-item-select':'')"
							@click="next(0)">
							设置
						</span>
						<span class="card-item" :class="(active==1?'card-item-select':'')" @click="next(1)">
							模组
						</span>
						<span class="card-item" :class="(active==2?'card-item-select':'')" @click="next(2)">
							世界
						</span>
					</div>
					<room v-show="active === 0" :loading1="loading1" :drawer="drawer" :model="model" :meme="meme"
						:size="size" :labelPosition="labelPosition"></room>

					<mod v-show="active === 1" @setMod="setMod" @ssMod="ssMod" @setSelect="setSelect"
						@setDrawer="setDrawer" :select="select" :modflag="modflag" :mod="mod" :modData="modData"
						:size="size" :labelPosition="labelPosition" :modList="modList" @setModListData="setModListData"
						@setModData="setModData"></mod>

					<view v-show="active === 2">
						<el-tag v-for="(value, key) in worldDataList" :key="key" closable :disable-transitions="false"
							@close="handleClose(key)" @click="setWorldIndex(key+1,value)">
							{{"世界"+(key+1)}}
						</el-tag>

						<el-button class="button-new-tag" size="small" @click="handleInputConfirm">+ 新增世界</el-button>
						<view v-if="worldIndex>0">
							<view v-if="worldData">
								<Master v-show="worldData" :type="worldMapData.includes('terrariumchest')?0:1"
									:world="worldData" @getWorld="getWorldData">
								</Master>
								<el-form :size="size" :model="model" ref="form2" label-width="130px"
									:label-position="labelPosition">
									<el-divider style="align-items: center;" title="地图资源代码配置">地图资源代码配置</el-divider>
									<el-input @blur="setWorldData" type="textarea" placeholder="请输入地面设置" :rows="15"
										v-model="worldMapData"></el-input>
								</el-form>
							</view>
							<view v-else>
								<worldMold :size="size" @copy="copy"></worldMold>
							</view>
						</view>
					</view>
				</el-card>
			</el-row>

			<el-drawer class="samintext" title="世界预设" :visible.sync="drawer" :with-header="false">
				<el-card v-if="active === 1 && select != 3">

					<el-row>
						<el-col>
							<el-form :size="size" :model="model" ref="form2" label-width="130px"
								:label-position="labelPosition">
								<el-divider style="align-items: center;" title="mod资源代码配置">mod代码配置
								</el-divider>
								<el-input @blur="setModData" type="textarea" placeholder="请输入mod设置" :rows="15"
									v-model="modList[index].config" v-if="modList.length >  0">
								</el-input>
							</el-form>
						</el-col>
					</el-row>
				</el-card>
				<el-card v-if="select == 3">

					<el-row v-loading="loading1">
						<el-col>
							<div class="block">

								<el-pagination small @current-change="handleCurrentChange" layout="prev, pager, next"
									:page-size="9" :total="total2">
								</el-pagination>
							</div>
							<div style="display: flex;flex-wrap: wrap;">
								<div class="demo-image__lazy"
									style="width: 32%;margin-right: 1%;margin-bottom: 1%;display: flex;flex-direction: column;justify-content: center;background-color: #e1e1e1;padding: 1%;box-sizing: border-box;"
									v-for="url in ssModList" :key="url.id">

									<div @click="addMod2(url)" v-popover:popover>
										<el-image style="width: 100%;min-height: 100px;" :src="url.img" lazy></el-image>
										<el-image :src="url.xjImg" lazy></el-image>
										<div class="demonstration">模组ID: {{ url.id }}</div>
										<div class="demonstration">模组名称: {{ url.name }}</div>
										<div class="demonstration">模组作者: {{ url.author }}</div>
									</div>
								</div>
							</div>
						</el-col>
					</el-row>
				</el-card>
			</el-drawer>

			<el-card style="margin-top: 20px;position: sticky;bottom: 0;z-index:10;">
				<view class=""
					style="display: flex;flex-wrap: wrap;justify-content: space-between;height: 80px;align-content: space-around;">
					<el-button :size="size" icon="el-icon-refresh-left" v-show="active === 0" @click="clearSetting()"
						type="warning">
						重置
					</el-button>
					<el-button style="margin: 0;" :size="size" type="primary" @click="save(1)">
						仅保存设置
					</el-button>
					<el-button style="margin: 0;" :size="size" type="primary" @click="save(3)">
						保存并重启
					</el-button>
					<el-button style="margin: 0;" :size="size" type="primary" @click="save(2)">
						生成新游戏
					</el-button>
				</view>

			</el-card>
		</view>

	</view>

</template>

<script>
	import Master from '../components/Master/Master.vue';
	import worldMold from '../setting/worldMold/worldMold.vue';
	import "./settingData.js"
	import room from './room/room.vue';
	import mod from './mod/mod.vue';
	const db = uniCloud.database();

	export default {
		data() {
			return {
				// 选择的世界下标
				worldIndex: 0,
				// mod搜索选择[1 模组ID 2 MOD链接 3 MOD名称]
				select: '',
				// 饥荒特殊符号集合
				meme: meme,
				// 世界数据集合
				worldMapDataList: [masterMapData1, masterMapData2, masterMapData3, masterMapData4, masterMapData5,
					masterMapData6, masterMapData7, cavesMapData1, cavesMapData2, cavesMapData3
				],
				// 加载
				loading: false,
				// mod搜索内容
				modurl: "",
				//[0 设置 1 模组 2 世界]
				active: 0,
				//世界最大人数
				max: 32,
				// 预设悬浮框
				drawer: false,
				// 房间设置基础参数
				model: {
					clusterDescription: undefined,
					clusterName: undefined,
					clusterPassword: undefined,
					gameMode: undefined,
					ip: "127.0.0.1",
					masterIp: undefined,
					maxPlayers: undefined,
					modDataList: undefined,
					pvp: undefined,
					shardEnabled: undefined,
					steamGroupId: undefined,
					token: undefined,
					type: undefined,
					voteEnabled: undefined,
					whitelistSlots: undefined,
					worldMapDataList: undefined,
					modDataList: undefined
				},
				// mod参数
				modData: undefined,
				// 当前选择的世界设置
				worldMapData: undefined,
				//0森林 1洞穴
				worldType: 0,
				labelPosition: 'left',
				size: 'medium',
				modflag: false,
				modInfo: {
					publishedfileid: '', //modid
					preview_url: '', //mod图片地址
					title: '', //mod名称
					time_updated: '', //mod更新时间
					time_created: '', //mod创建时间
					config: ''
				},
				mod: {
					publishedfileid: '', //modid
					preview_url: '', //mod图片地址
					title: '', //mod名称
					time_updated: '', //mod更新时间
					time_created: '', //mod创建时间
					config: ''
				},
				// 世界设置集合
				worldDataList: [],
				ssModText: '',
				ssModList: [],
				modList: [],
				modId: "",
				worldData: new Map(),
				index: 0,
				total2: 0,
				loading1: true,
				visible: false,
				world: 1
			}
		},
		components: {
			Master,
			room,
			mod,
			worldMold
		},
		created() {
			//拉取服务器信息
			this.modflag = false;
			this.getConfig();
			this.getLabelPosition()
		},
		mounted() {
			window.onresize = () => {
				this.getLabelPosition()
			}
		},
		methods: {
			getWorldData(val, inx) {
				let worldData = this.worldDataList[this.worldIndex - 1]
				let split = worldData.split(',\n    ' + val + '="')
				let i1 = split[1].indexOf('"')
				let split2 = split[1].substring(i1, split[1].length)
				this.worldDataList[this.worldIndex - 1] = split[0] + ',\n    ' + val + '="' + inx + split2
				this.worldMapData = this.worldDataList[this.worldIndex - 1]
			},
			setWorldIndex(k, v) {
				if (this.worldDataList) {
					this.worldMapData = this.worldDataList[k - 1]
					this.worldIndex = k
					if (this.worldMapData) {
						this.setWorldData()
					} else {
						this.worldData = undefined
					}
				}
			},
			handleClose(tag) {
				this.worldDataList.splice(this.worldDataList.indexOf(tag), 1);
				this.setWorldIndex(1)
			},
			handleInputConfirm() {
				this.worldDataList.push("")
				console.log(this.worldDataList);
			},
			ssMod(val1, val2, val3) {
				this.ssModList = val1
				this.ssModText = val2
				this.total2 = val3
			},
			setSelect(val) {
				this.select = val
			},
			setDrawer(val1, val2) {
				if (val1) {
					this.drawer = val1
				}
				this.loading1 = val2

			},
			setModListData(val) {
				this.modList = val
			},
			setModList() {
				this.modList = []
				if (this.model) {
					let str = this.model.modData
					let arr = str.split('["workshop-')
					for (var i = 1; i < arr.length; i++) {
						let i1 = arr[i].indexOf('"]')
						this.modId = arr[i].substring(0, i1)
						let i2 = arr[i].indexOf('configuration')
						let i3 = arr[i].indexOf('enabled=true')
						this.getMod1(this.modId, arr[i].substring(i2, i3))
					}

				}
			},
			setModData(modList) {
				let data1 = '["workshop-'
				let data2 = '"]={'
				let data3 = 'enabled=true },\n'
				// let data3 = '}'
				let modData = 'return {\n'
				if(modList){
						modList.forEach(item => {
							modData = modData + data1 + item.publishedfileid + data2 + item.config + data3
						})
				}else{
					if (this.modList) {
						this.modList.forEach(item => {
							modData = modData + data1 + item.publishedfileid + data2 + item.config + data3
						})
					}
				}
				
				modData += '}'
				this.model.modData = modData
			},

			setWorldData() {
				if (this.worldMapData) {
					let regexp = /[a-zA-Z_]{2,}/g
					let str111 = "overrides={"
					let str112 = this.worldMapData.substring(this.worldMapData.indexOf(
						str111) + str111.length, this.worldMapData.length)
					str112 = str112.substring(0, str112.indexOf("}"))
					let arr111 = str112.match(regexp)
					let arr = new Map();
					for (var i = 0; i < arr111.length; i = i + 2) {
						arr.set(arr111[i], arr111[i + 1])
					}
					this.worldData = arr
				}

			},
			handleCurrentChange(val) {
				this.loading1 = true;
				this.$http.get("http://mgfwg.qtkjcn.com/chat/getMod?p=" + val + "&str=" + this.modurl).then((data) => {
					this.ssModList = data.list
					this.loading1 = false;
				})
			},
			setMod(index) {
				this.drawer = true
				this.select = 2
				this.index = index
			},
			addMod2(val) {
				let flag = false
				this.modList.forEach(item => {
					if (item.publishedfileid == val.id) {
						this.$message({
							message: 'MOD重复添加',
							type: 'warning'
						});
						flag = true
						return
					}
				})
				if (!flag) {
					this.mod.preview_url = val.img
					this.mod.publishedfileid = val.id
					this.mod.title = val.name
					this.modflag = true;
					this.mod._id = undefined;
					db.collection('mod_list').add({
						preview_url : val.img,
						publishedfileid : val.id,
						title : val.name,
						_id : undefined
					})
					this.mod.config = "configuration_options={  },"
					let list = this.modList
					list.push(this.mod)
					this.setModData(list)
					this.$message({
						message: 'MOD添加成功',
						type: 'success'
					});
				}
			},
			getLabelPosition() {
				let windowWidth = window.innerWidth

				if (windowWidth < 768) {
					this.labelPosition = 'top'
					this.size = 'mini'
				} else {
					this.labelPosition = 'left'
					this.size = 'medium'
				}

			},
			copy(val) {

				this.worldMapData = this.worldMapDataList[val];
				this.worldDataList[this.worldIndex - 1] = this.worldMapDataList[val];
				this.setWorldData()
				this.successMessage('设置成功');
			},
			save(type) {
				let that = this
				uni.showModal({
					content: "确认执行操作吗?",
					success: function(res) {
						if (res.confirm) {
							that.model.type = type;
							that.model.worldDataList = this.worldDataList
							that.model.modDataList = [this.modData ? this.modData : ""]
							that.$http.post("/setting/saveConfig", that.model).then((data) => {
								if (data.code != 0) {
									that.warningMessage(data.message);
								} else {
									that.successMessage("成功");
									that.active = 0;
									that.getConfig();
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})

			},
			getConfig() {
				this.modList = []
				let str = ""
				let arr = []
				this.$http.get("/setting/getConfig").then((data) => {

					if (data.code == 0 && data.data) {
						this.model = data.data;
						this.worldDataList = data.data.worldMapDataList
						this.modData = data.data.modDataList[0] ? data.data.modDataList[0] : '';
						this.model.ip = data.data.ip ? data.data.ip : '127.0.0.1'

						if (this.model) {
							str = this.modData
							if (this.modData) {
								arr = str.split('["workshop-')
								for (var i = 1; i < arr.length; i++) {
									let i1 = arr[i].indexOf('"]')
									this.modId = arr[i].substring(0, i1)

									let i2 = arr[i].indexOf('configuration')
									let i3 = arr[i].indexOf('enabled=true')
									this.getMod1(this.modId, arr[i].substring(i2, i3))
								}
							}

						}
					}
				})
			},
			getMod2(mod) {
				db.collection('mod_list').add({
					"preview_url": mod.preview_url,
					"publishedfileid": mod.publishedfileid,
					"title": mod.title,
				}).then((res) => {
					this.modList.push(mod)
				}).catch((err) => {
					console.log(err);
				})

			},
			getMod1(modId, config) {
				db.collection("mod_list").where({
						'publishedfileid': modId
					}).get().then((res) => {
						let {
							result: r2
						} = res
						let r3 = r2.data[0]
						if (r3) {
							this.modInfo = {
								...r3,
								'config': config
							}
							this.modList.push(this.modInfo)
						} else {
							this.$http.get("http://117.72.51.98:8088/getMod?modId=" + modId).then((
								data) => {
								let mod = {}
								mod.preview_url = data.img
								mod.publishedfileid = data.id
								mod.title = data.name
								mod._id = undefined
								mod.config = config
								console.log(mod);
								this.getMod2(mod)
							})
						}
					})
					.catch((err) => {
						uni.showModal({
							content: err.message || '查询失败',
							showCancel: false
						})
					})
			},
			clearSetting() {
				let tmp = {
					clusterIntention: 'social',
					clusterName: undefined,
					clusterDescription: undefined,
					gameMode: 'survival',
					pvp: false,
					maxPlayers: 6,
					steamGroupId: "43220089",
					clusterPassword: undefined,
					token: undefined,
					masterMapData: this.masterMapData1,
					cavesMapData: this.cavesMapData1,
					modData: undefined,
					type: 1,
					ip: "127.0.0.1"
				};
				this.model = tmp;
			},
			next(val) {
				this.active = val;
				if (val != 0) {
					if (val == 2) {
						this.setWorldIndex(1, this.worldDataList)
					}
					this.loading = true
					setTimeout(() => {
						this.loading = false
					}, 500)
				}
			},
			successMessage(message) {
				this.$message({
					message: message,
					type: 'success'
				});
			},
			warningMessage(message) {
				this.$message({
					message: message,
					type: 'warning'
				});
			},
		}
	}
</script>

<style scoped>
	>>>.el-input {
		margin-right: 20px;
	}

	>>>.el-form-item__content {
		display: flex;
	}

	>>>.uni-container {
		padding: 0 10px;
	}

	.text {
		font-size: 14px;
	}

	.item {
		margin-bottom: 18px;
	}

	.clearfix:before,
	.clearfix:after {
		display: table;
		content: "";
	}

	.clearfix:after {
		clear: both
	}

	.box-card {
		width: 480px;
	}

	.mybtn-warn {
		background-color: #e43d33;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.mybtn-warn-select {
		background-color: #8f939c;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.mybtn-warn {
		background-color: #e43d33;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.mybtn-warn-select {
		background-color: #8f939c;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.mybtn-success {
		background-color: #67C23A;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.mybtn-success-select {
		background-color: #409EFF;
		color: #ffffff;
		/* box-shadow: 2rpx 0rpx 2rpx 5rpx #ee3d2d; */
	}

	.card-item-first {
		border-radius: 10px 0 0 0;
	}

	.card-item-last {
		border-radius: 0 10px 0 0;
	}

	.card-item {
		display: inline-block;
		padding: 20rpx 30rpx;
		border: #409EFF 2px solid;
		/* background-color: #00aaff; */
		border-radius: 10px;
		color: #353535;
		margin-right: 10px;
		cursor: pointer;
	}

	.card-item-select {
		display: inline-block;
		padding: 20rpx 30rpx;
		border: #ffaa00 2px solid;
		/* background-color: #ffaa00; */
		border-radius: 10px;
		color: #353535;
		margin-right: 10px;
	}

	.clearfix {
		/* font-size: 20rpx; */
	}

	.samintext {
		font-size: 20rpx;

	}

	>>>.el-card__body {
		padding: 20rpx;
	}

	.el-tag+.el-tag {
		margin-left: 10px;
	}

	.button-new-tag {
		margin-left: 10px;
		height: 32px;
		line-height: 30px;
		padding-top: 0;
		padding-bottom: 0;
	}

	.input-new-tag {
		width: 90px;
		margin-left: 10px;
		vertical-align: bottom;
	}
</style>